/**
 * 订单 优惠券结算
 */
require(['jquery','../modules/pageSize','../modules/popup'], function($, pageSetSize, popup){
    //设置html根目录字体大小
    setRootFontSize(pageSetSize);
    var couponList = [];
    var deductList = [];
    var curCouponIndex = -1;
    var packageList = [];
    var _allCounps = {};
    var _lastPrice = $('#last_price').data('all');
    var _realLastPrice = _lastPrice;
    var _realDiscount = "0.00";
    var _realDkNum = "0.00";
    var curCoupon;
    function getRepeatPos(index, val){
        var pos = -1;
        var clist = couponList[index];
        for(var i = 0; i < clist.length; i++){
            if(clist[i] == val){
                pos = i;
                break;
            }
        }
        return pos;
    }
    function removeVal(index, val){
        var pos = getRepeatPos(index, val);
        if(pos != -1){
            couponList[index].splice(pos, 1);
        }
    }
    function updateToAllCoupons(){
        $(".coupon-tips li").each(function(i, o){
            if($(this).hasClass("active")){
                _allCounps["$"+$(this).attr("data-id")] = true;
            }else if(!$(this).hasClass("disable")){
                _allCounps["$"+$(this).attr("data-id")] = false;
            }
        });
    }
    function choseHadItems(index){
        var clist = couponList[index];
        var tlis = $('.coupon-tips li');
        tlis.removeClass('active').removeClass('disable');
        for(var i = 0; i < clist.length; i++){
            tlis.eq(clist[i]).addClass('active');
        }
        $(".coupon-tips li").each(function(i, o){
            if(!$(this).hasClass("active") && _allCounps["$"+$(this).attr("data-id")]){
                $(this).addClass("disable");
            }           
        });
    }
    function updateCouponEvent(){
        $('.coupon-tips li').on('click',function(){
            if($(this).hasClass("disable")){
                return;
            }
            var _index = $(this).index();
            var _cpindex = curCouponIndex;
            var _cOldRealCost = packageList[_cpindex].realCost;
            if(!$(this).hasClass("active")){
                if($(this).hasClass("only")){
                    var _dIndex = packageList[_cpindex].dk_index;
                    var _flag = true;
                    var _used = false;
                    if(_dIndex != -1){
                        var _dt = deductList[_dIndex];
                        if(_dt["used"]){
                            var ptmoney = getFixedFloat(packageList[_cpindex].total, $(this).attr("data-money"), "-");
                            ptmoney = getFixedFloat(ptmoney, _dt["cost"], "-");
                            if(parseFloat(ptmoney) > 0){
                                packageList[_cpindex].realCost = ptmoney;
                                _used = true;
                            }else{
                                _flag = false;
                            }
                        }
                    }
                    if(_flag){
                        if(!_used){
                            packageList[_cpindex].realCost = getFixedFloat(packageList[_cpindex].total, $(this).attr("data-money"), "-");
                        }
                        couponList[_cpindex] = [];
                        couponList[_cpindex].push(_index);
                        packageList[_cpindex].isNoFeeUsed = false;
                        $(this).siblings().removeClass('active');
                        $(this).addClass('active');
                    }
                }else if($(this).hasClass("no-fee") && packageList[_cpindex].free == 0){
                    var diff = getFixedFloat(packageList[_cpindex].realCost, packageList[_cpindex].fee, "-");
                    if(parseFloat(diff) <= 0){
                        return;
                    }
                    if(!packageList[_cpindex].isNoFeeUsed && parseFloat(packageList[_cpindex].fee) > 0){
                        packageList[_cpindex].isNoFeeUsed = true;
                        couponList[_cpindex].push(_index);
                        packageList[_cpindex].realCost = getFixedFloat(packageList[_cpindex].realCost, packageList[_cpindex].fee, "-");
                        $(this).addClass('active');
                    }
                }else{
                    $(this).siblings('.only').each(function (i, o) {
                        if($(o).hasClass('active')){
                            packageList[_cpindex].realCost = getFixedFloat(packageList[_cpindex].realCost, $(o).attr("data-money"), "+");
                            removeVal(_cpindex, $(o).index());
                            $(o).removeClass('active');
                        }
                    });
                    var pdmoney = getFixedFloat(packageList[_cpindex].realCost, $(this).attr("data-tomoney"), "-");
                    if(packageList[_cpindex].free == 0){
                        pdmoney = getFixedFloat(pdmoney, packageList[_cpindex].fee, "-");
                    }
                    var ptmoney = getFixedFloat(packageList[_cpindex].realCost, $(this).attr("data-money"), "-");
                    // 减去用户优惠券后大于0才进行选取操作
                    if(parseFloat(pdmoney) >= 0 && parseFloat(ptmoney) > 0){
                        couponList[_cpindex].push(_index);
                        packageList[_cpindex].realCost = getFixedFloat(packageList[_cpindex].realCost, $(this).attr("data-money"), "-");
                        $(this).addClass('active');
                    }
                }
            }else{
                if($(this).hasClass("only")){
                    packageList[_cpindex].realCost = packageList[_cpindex].total;
                }else if($(this).hasClass("no-fee")){
                    packageList[_cpindex].isNoFeeUsed = false;
                    packageList[_cpindex].realCost = getFixedFloat(packageList[_cpindex].realCost, packageList[_cpindex].fee, "+");
                }else{
                    packageList[_cpindex].realCost = getFixedFloat(packageList[_cpindex].realCost, $(this).attr("data-money"), "+");
                }
                removeVal(_cpindex, _index);
                $(this).removeClass('active');
            }
            updateToAllCoupons();
            var diff = getFixedFloat(_cOldRealCost, packageList[_cpindex].realCost, "-");
            if(diff.indexOf("-") == 0){
                _realLastPrice = getFixedFloat(_realLastPrice, diff.substr(1), "+");
                _realDiscount = getFixedFloat(_realDiscount, diff.substr(1), "-");
            }else{
                _realLastPrice = getFixedFloat(_realLastPrice, diff, "-");
                _realDiscount = getFixedFloat(_realDiscount, diff, "+");
            }
            packageList[_cpindex].pktEL.text("￥"+packageList[_cpindex].realCost);
            $('#lj_real_discount').text("￥"+_realDiscount);
            $('#last_price').text("￥"+_realLastPrice);
            var nums = couponList[_cpindex].length;
            if(nums > 1){
                curCoupon.text("已选"+nums+"个优惠券");
            }else if(nums == 1){
                curCoupon.text($('.coupon-tips li').eq(couponList[_cpindex][0]).text());
            }else{
                curCoupon.text("请选择");
            }
        });
    }
    //付款方式
    $('.pay-method li').on('click',function(){
        $(this).addClass('active').siblings().removeClass('active');
    });
    //物流方式显示
    $('.delivery').each(function(){
        if($(this).find('.logistic-method').text()=='自提'){
            $(this).find('.zt-address').show();
        }
        else{
            $(this).find('.zt-address').hide();
        }
    });
    $(".coupondis li").each(function(){
        _allCounps["$"+$(this).attr("data-id")] = false;
    });
    //优惠券使用
    $('.coupon-use a').each(function(i, o){
        couponList.push([]);
        var cp = $(this).parents('.order-package');
        // isNoFeeUsed 是否使用免邮券  free 是否免邮费(0:未免邮费 1:免邮费)
        var _i = packageList.length;
        packageList.push({total: cp.attr("data-total"), fee: cp.attr("data-fee"), free: parseInt(cp.attr("data-free")), realCost: cp.attr("data-total"), isNoFeeUsed: false, pktEL: cp.find(".package-total"), dk_index : -1});
        cp.attr("data-index", _i);
        $(o).on('click',function(){
            if(curCouponIndex != i){
                curCouponIndex = i;
                curCoupon = $(o);
                $('.coupon-tips li').off('click');
                $('.coupon-tips ul').html($(this).parents(".order-package").children(".coupondis").html());
                updateCouponEvent();
            }
            choseHadItems(curCouponIndex);
            popup.popupSlide('.coupon-tips');
        });
    });    
    $('.coupon-tips a').on('click',function(){
        $(this).parents('.coupon-tips').slideUp(200);
        $('.pop-mask').remove();
    });
    $(".deduct-use").each(function(i, o){        
        var cp = $(this).parents('.order-package');
        var _i = deductList.length;
        var _cpIndex = parseInt(cp.attr("data-index") || - 1);
        if(_cpIndex != -1){
            packageList[_cpIndex].dk_index = _i;
        }
        deductList.push({"tpl": $(this).html(),"total": cp.attr("data-total"), "realCost": cp.attr("data-total"), "used": false, "price" : cp.attr("data-dkPrice"), "cost" : "0.00", "pktEL": cp.find(".package-total"), "cp_index" : _cpIndex});
        $(o).on('click',function(){
            var _dt = deductList[i];
            var pkg = null;
            if(_dt["cp_index"] != -1){
                pkg = packageList[_dt["cp_index"]];
            }           
            var _dkNum = _dt["used"] ? _dt["cost"] : _dt["price"];
            if(pkg != null){
                _dt["realCost"] = pkg.realCost;
            }
            var _total = _dt["realCost"];
            if($(this).hasClass('active')){
                $(this).removeClass('active');
                _dt["cost"] = "0.00";
                _realDkNum = getFixedFloat(_realDkNum, _dkNum, "-");
                _realLastPrice = getFixedFloat(_realLastPrice, _dkNum, "+");
                _dt["realCost"] = getFixedFloat(_dt["realCost"], _dkNum, "+");
                _dt["used"] = false;
				$(this).html(_dt["tpl"]);
            }else{
                $(this).addClass('active');
                _diff = parseFloat(getFixedFloat(_dt["realCost"], _dkNum, "-"));
                if(_diff < 0){
                    _dkNum = _dt["realCost"];
                }
                _dt["cost"] = _dkNum;

                _realDkNum = getFixedFloat(_realDkNum, _dkNum, "+");
				_off = getFixedFloat(_dt["price"], _dt["cost"], "-");
                _realLastPrice = getFixedFloat(_realLastPrice, _dkNum, "-");
                _dt["realCost"] = getFixedFloat(_dt["realCost"], _dkNum, "-");
                _dt["used"] = true;
				$(this).html("已经抵扣"+_dt["cost"]+"现金,剩余可抵扣"+_off+"现金");
            }
            if(pkg != null){
                pkg.realCost = _dt["realCost"];
            }
            _dt["pktEL"].text("￥"+_dt["realCost"]);            
            $('#jj_dknum').text("￥"+_realDkNum);
            $('#last_price').text("￥"+_realLastPrice);            
        });
    });

    //用户下单
    //结算
    $('.order-settment-btn').on('click',function () {
        /*判断需要选择支付方式*/

        var pay = $('.pay-method').find('.active span').text();
        //console.log($('.pay-method').find('.active span').text());
        if(pay ==''){
            popup.alertPopup('请选择支付方式!');
            return false;
        }

        //使用优惠卷
        var count=$('.order-package').length;
        var orders=new Object();
        orders.order=new Object();
        var _cindex = 0;
        var _cNindex = 0;
        var _cfound = false;
        var _cNfound = false;
        $('.order-package').each(function(i){
            var pnum=$(this).find('.goods-item').length;
            var groupnum=$(this).find('.goods-item .group').length;
            //console.log(groupnum);
            orders.order[i]=new Object();
            orders.order[i].items=new Object();
            orders.order[i].coupons=[];
            orders.order[i].bonus='';
            $(this).find('.goods-item').each(function(j){
                orders.order[i].items[j]=new Object();
                orders.order[i].items[j].product_name=$(this).find('.name').text();
                orders.order[i].items[j].cart_num =$(this).find('.fr').text();
                orders.order[i].items[j].price = $(this).find('.data_price').text();
                orders.order[i].items[j].spec_info = $(this).find('.norms').text();
                orders.order[i].items[j].group_id = $(this).data('gid');
                orders.order[i].items[j].type = $(this).data('type');
                orders.order[i].items[j].product_id = $(this).data('pid');
                orders.order[i].items[j].local_id = $(this).data('lid');
                //console.log($(this).data('pid'));
            })
            _cfound = false;
            $(this).find('.coupondis').each(function (m,o) {
                _cfound = true;
                var klist = couponList[_cindex];
                var cur;
                
                for(var k=0;k<klist.length;k++){
                    cur =  $(this).children("li").eq(klist[k]);
                    orders.order[i].coupons.push([cur.data('id'),cur.data('did'),cur.data('lid')]);
                }
            });
            _cNfound = !!$(this).find('.deduct-use').length;
            if(_cNfound){
                var _dt = deductList[_cNindex];
                 orders.order[i].bonus = _dt["cost"];
            }



            if(!_cfound){
                delete orders.order[i].coupons;
            }
            if(!_cNfound){
                delete orders.order[i].bonus;
            }


            orders.order[i].local_id = $(this).find('.package-name').data('lid');
            orders.order[i].expected_time = $(this).find('.expect-time').text();
            orders.order[i].shipping = $(this).find('.logistic-method').data('id');
            orders.order[i].msg = $(this).find('.package-msg').val();
            orders.order[i].cost_freight = _cfound ? packageList[_cindex].fee : $(this).data("fee");
                //$(this).find('.ship_fee em').text();
            orders.order[i].cost_item = $(this).find('.package-total').data('costitem');
            //orders.order[i].total_amount = $(this).find('#local_total').text();
            orders.order[i].pay_method = $('.pay-method').find('.active span').text();
            orders.order[i].pay_method_id = $('.pay-method').find('.active span').data('id');
            orders.order[i].receipt_name = $('.address').find('#receipt').text();
            orders.order[i].ship_mobile = $('.address').find('#mobile').text();
            orders.order[i].ship_area = $('.address').find('#addrpriv').text();
            orders.order[i].ship_addr = $('.address').find('#adddetaile').text();
            orders.order[i].local_name = $('.package-name').find('.fr').text();
            //orders.order[i].local_total = (_cfound || _cNfound) ? packageList[_cindex].realCost : $(this).data("total");
            var _total = $(this).data("total");
            if(_cfound){
                _total = packageList[_cindex].realCost;
            }else if(_cNfound){
                _total = deductList[_cNindex].realCost;
            }
            orders.order[i].local_total = _total;


            /***************冉 3-14 支付ID********************/
            orders.pay_method_id = $('.pay-method').find('.active span').data('id');
            /************************************************/
            orders.order[i].pickedup_bn = $(this).find('.package-name').data('m');
            if(_cfound){
                _cindex++;
            }
            if(_cNfound){
                _cNindex++;
            }
            //orders.order[i].item=items;
        })
         //console.log(orders);
        //console.log(JSON.stringify(orders));
        $.ajax({
            url: '/Home/Orders/cartOrder'+getFixedExtraUrl(),
            type:'post',
            dataType: 'json',
            data:{data:orders},
            success: function (data) {
                if(data.status == 0){
                    popup.alertPopup(data.msg);
                }else if(data.status == 1){
                    popup.alertPopup(data.msg);
                    //console.log(data.url);
                    window.location.href = data.url;
                }

            },
            error: function () {
                popup.alertPopup('参数错误');
            }
        })
    })



});